package com.boot.stomp;

import com.boot.stomp.authentication.StompAuthenticationHandler;
import com.boot.stomp.client.AccountClient;
import com.boot.stomp.client.AccountInfo;
import com.boot.web.http.HttpModel;
import com.sun.security.auth.UserPrincipal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;

import java.security.Principal;
import java.util.Objects;

@Slf4j
public class TokenAuthenticationHandler implements StompAuthenticationHandler {

    private final AccountClient accountClient;

    public TokenAuthenticationHandler(AccountClient accountClient) {
        this.accountClient = accountClient;
    }

    @Override
    public Principal getPrincipal(StompHeaderAccessor accessor) {
        String token = accessor.getFirstNativeHeader("Authorization");
        try {
            ResponseEntity<HttpModel<AccountInfo>> accountInformation = accountClient.getAccountInformation(token);
            if (!accountInformation.getStatusCode().equals(HttpStatus.OK)) {
                log.info("用户验证失败：{}", token);
                return null;
            } else {
                AccountInfo info = Objects.requireNonNull(accountInformation.getBody()).getData();
                return new UserPrincipal(info.getUsername());
            }
        } catch (RuntimeException e) {
            System.out.println(e);
            return null;
        }
    }
}
